﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using SPerfMonitor;

namespace SPerfMonitor
{
    public class PerfMonitor : PerfMonitorClient
    {
        
        public I_PerfDetails getPerfDetails()
        {
            I_PerfDetails temp;
            temp = new Detail();

            temp.CpuUsage = getCPUCounter();
            temp.RamUsage = memoire();
            temp.DDUsage = GetHDDFreeSpace("");
            temp.isAllowedToStart();

            return temp;
        }

        public int getCPUCounter()
        {

            PerformanceCounter cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";

            // will always start at 0
            dynamic firstValue = cpuCounter.NextValue();
            System.Threading.Thread.Sleep(1000);
            // now matches task manager reading
            dynamic secondValue = cpuCounter.NextValue();

            return (int)secondValue;
        }

        public int memoire()
        {
            int temp = 0;

            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_OperatingSystem");

            foreach (ManagementObject queryObj in searcher.Get())
            {
                double free = Double.Parse(queryObj["FreePhysicalMemory"].ToString());
                double total = Double.Parse(queryObj["TotalVisibleMemorySize"].ToString());
                temp = Convert.ToInt32(Math.Round(((total - free) / total * 100), 2));
            }

            return temp;
        }

        public double GetHDDFreeSpace(string drive)
        {
            //check to see if the user provided a drive letter
            //if not default it to "C"
            if (drive == "" || drive == null)
            {
                drive = "C";
            }
            //create our ManagementObject, passing it the drive letter to the
            //DevideID using WQL
            ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"" + drive + ":\"");
            //bind our management object
            disk.Get();
            //return the free space amount
            return Convert.ToDouble(disk["FreeSpace"]);
        }
    }
}
